package example.listview;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import example.listview.R;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.google.appengine.preferencessync.SyncUtils;

/**
 * This class demonstrates the use of SyncUtils.
 */
public class ListViewActivity extends Activity {
  public static final String PREFERENCES_NAME = "preference";

  private SharedPreferences sharedPreferences;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    sharedPreferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME,
        Context.MODE_PRIVATE);
    
    configureSync();
 
    refreshView();


    Button addButton = (Button) findViewById(R.id.add);
    addButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        onClickAdd();
      }
    });
    
    Button deleteButton = (Button) findViewById(R.id.delete);
    deleteButton.setOnClickListener(new OnClickListener() {
      
      @Override
      public void onClick(View v) {
        onClickDelete();
      }
    });

    Button syncButton = (Button) findViewById(R.id.sync);
    syncButton.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        onPressSync();
      }
    });
    
    Button refreshButton = (Button) findViewById(R.id.refresh);
    refreshButton.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        refreshView();
      }
    });
 
  }

  private void onClickAdd() {
    String key = ((EditText) findViewById(R.id.key)).getText().toString();
    String value = ((EditText) findViewById(R.id.value)).getText().toString();

    if (key.trim().isEmpty() || value.trim().isEmpty()) {
      return;
    }

    Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
    
    refreshView();
  }
  
  private void onClickDelete() {
    String key = ((EditText) findViewById(R.id.key)).getText().toString();
    
    if (key.trim().isEmpty()) {
      return;
    }
    
    Editor editor = sharedPreferences.edit();
    editor.remove(key);
    editor.commit();
    
    refreshView();
  }

  private void onPressSync() {
    // Call Sync. This in turn triggers sync in the sync adapter.
    SyncUtils.doSync(getApplication());
  }

  private Map<String, String> getSharedPrefsMap() {
    TreeMap<String, String> orderedMap = new TreeMap<String, String>();
    if (sharedPreferences.getAll() == null) {
      return orderedMap;
    }
    for (Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) {
      orderedMap.put(entry.getKey().trim(), ((String) entry.getValue()).trim());
    }
    return orderedMap;
  }

  private void refreshView() {
    ListView lview = (ListView) findViewById(R.id.listview);
    ListViewAdapter adapter = new ListViewAdapter(this, getSharedPrefsMap());
    lview.setAdapter(adapter);
  }
  
  public void configureSync() {
      Account[] accounts = AccountManager.get(getApplicationContext()).getAccountsByType("com.google");
      if (accounts.length == 0) {
        return;
      }

      // Call GcmIntentService to register your device.
      GCMIntentService.register(getApplicationContext());

      // Specify the google account to be used. Here we use the first google account available.
      SyncUtils.setUsername(getApplicationContext(), accounts[0].name);

      // Specify your preference file which needs to be synced.
      SyncUtils.addPreferences(getApplicationContext(), PREFERENCES_NAME);

      // Set the server url. This url is for the emulator to connect to the appengine localhost.
      SyncUtils.setSyncServerUrl(getApplicationContext(), "http://10.0.2.2:8888/");
  }
}
